package com.example.netty.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer{
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(9000);
        while (true){
            System.out.println("等待连接");
            // 阻塞等待
            Socket client = serverSocket.accept();
            System.out.println("有客户端连接了");
            handleRead(client);
        }
    }

    /**
     *
     * @param client
     */
    private static void handleRead(Socket client) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] bytes = new byte[1024];
                try {
                    int read = client.getInputStream().read(bytes);
                    System.out.println("客户端发送过来的数据为："+new String(bytes,0,read));
                    // 手动阻塞
                    Thread.sleep(Integer.MAX_VALUE);
                    client.getOutputStream().write("你好，我收到你的数据了".getBytes());
                    client.getOutputStream().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                }
            }
        }).start();

    }
}